package model;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Observable;
import java.util.Vector;

public class SearchContact extends Observable{

	public static SearchContact cnt = null;
	public static Vector<Account> search = new Vector<Account>();
	public static SearchContact cntAdm = null;

	public SearchContact(){
		cnt = this;
		cntAdm=this;
	}
	public void Search(String txt) {
		try {
			search.clear();
			if (!txt.contains("%")){
				String replaced="";
				if (txt.contains("*"))
					for (int i = 0; i<txt.length();i++)
						if (txt.charAt(i)=='*')
							replaced+="%";
						else
							replaced+=txt.charAt(i);
				else
					replaced=txt;
				ResultSet match = Database.getQueryResult("SELECT * FROM account WHERE f_name LIKE '"+replaced+"%' OR s_name LIKE '"+replaced+"%'");
				int id;
				while (match.next())
					if (match.getInt("acc_id")!=Database.Utente.getID() && match.getInt("level")!=512  ){
						Account a = new Account(match.getInt("acc_id"),
								match.getString("photo"),
								match.getString("f_name"),
								match.getString("s_name"),
								match.getInt("sex"));
						search.add(a);

					}
				for (int i=0;i<search.size();i++){
					id = search.get(i).getID();
					search.get(i).setEmail(Email.accEml(id));
					search.get(i).setIndirizzo(Indirizzo.accAdr(id));
					search.get(i).setTelefono(Telefono.accTel(id));
				}
				if (Database.Utente.getLevel()==512)
					search.add(Database.Utente);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/*public void uppdater(){
		setChanged();
		notifyObservers();
	}
	 */
	public void updateForUser() {
		setChanged();
		notifyObservers(false);
	}
	public void updateForAdmin() {
		setChanged();
		notifyObservers(true);
	}
}
